package com.cema.manage.project.manage;

import cn.hutool.core.date.DateUtil;
import com.cema.manage.common.exception.BizException;
import com.cema.manage.project.enums.RedisEnum;
import com.cema.manage.redis.RedisService;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/ueditor")
public class UeditorController {

    @Resource
    private RedisService redisService;

    private String[] imageAllowFiles = {".png", ".jpg", ".jpeg", ".gif"};

    @RequestMapping()
    public Object ueditor(String action, MultipartFile upfile, HttpServletRequest req, HttpServletResponse resp) {
        String storageAddress = (String) redisService.get(RedisEnum.FILE_STORAGE_ADDRESS.getKey());
        String downloadAddress = (String) redisService.get(RedisEnum.FILE_DOWNLOAD_ADDRESS.getKey());
        if ("config".equals(action)) {
            Map<String, Object> config = new HashMap<String, Object>();
            config.put("imageActionName", "uploadimage");
            config.put("imageUrlPrefix", downloadAddress);
            config.put("imagePath", storageAddress);
            config.put("imageFieldName", "upfile");
            config.put("imageMaxSize", 20480000);
            config.put("imageAllowFiles", imageAllowFiles);
            return config;
        } else if ("uploadimage".equals(action)) {
            if (upfile.isEmpty()) {
                throw new BizException("上传文件不能为空");
            }

            String filename = upfile.getOriginalFilename();

            String suffix = filename.substring(filename.lastIndexOf("."), filename.length());

            String uuid = UUID.randomUUID().toString();

            String currDate = DateUtil.format(new Date(), "yyyyMMdd");

            try {
                FileUtils.writeByteArrayToFile(new File(storageAddress + "/fileupload/" + currDate + "/" + uuid + suffix), upfile.getBytes());
                Map<String, String> result = new HashMap<String, String>();
                result.put("state", "SUCCESS");
                result.put("type", suffix);
                result.put("size", String.valueOf(upfile.getSize()));
                result.put("url", "/fileupload/" + currDate + "/" + uuid + suffix);
                return result;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @GetMapping("config")
    public void config() {

    }
}
